package meijuli.com.join51.business.fragment;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.Map;
import com.jhx.common.utils.Constants;
import meijuli.com.join51.business.R;
import meijuli.com.join51.business.TimerService;
import meijuli.com.join51.business.activity.MainActivity;
import meijuli.com.join51.business.app.MApplication;

import com.jhx.common.cache.SimpleCache;
import com.jhx.common.model.DeviceInfo;
import com.jhx.common.utils.SystemUtil;
import com.jhx.common.http.ApiManager;
import com.jhx.common.http.HttpRequest;
import com.jhx.common.http.HttpResponse;
import com.jhx.common.http.ResponseCallback;
import meijuli.com.join51.business.model.EventBean;
import meijuli.com.join51.business.model.SmsCode;
import meijuli.com.join51.business.model.UserData;
import meijuli.com.join51.business.service.ApiService;
import meijuli.com.join51.business.utils.SoftInputUtil;
import meijuli.com.join51.business.utils.StringUtil;
import com.jhx.common.utils.ToastUtil;
import com.jhx.common.utils.UserManager;
import retrofit2.Call;

import static android.content.ContentValues.TAG;

/**
 * 注册页面
 *
 * @author jack
 */
public class RegisterFragment extends BaseFragment implements View.OnClickListener {
    EditText mRecommendPhone;
    EditText mMobileInputView;
    Button mGetAuthCodeBtn;
    EditText mVerifyCodeView;
    EditText mPasswordInputView;
    CheckBox mAgreeServiceCheckBox;
    TextView mPrivacyView;
    Button mNextStepBtn;
    EditText mPasswordInputViewAgain;
    Toolbar mToolbar;
    TextView mTitleTxt;
    TextView mLoginTxt;
    private static final int TOTAL_COUNT_TIME = 120;
    private static final int USER_TYPE = 2;
    private TimerService.TimerServiceBinder timerServiceBinder;
    private boolean isBind = false;
    private Call<HttpResponse<SmsCode>> call;
    private Call<HttpResponse<UserData>> mCall;
    /**
     * 密码规则，必须是数字和字母组合，并且在6-16位之间
     */
    private String regex = "^[0-9A-Za-z]{6,16}$";

    private ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            timerServiceBinder = (TimerService.TimerServiceBinder) service;
            isBind = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            timerServiceBinder.stopTimerService();
            isBind = false;
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_register_new, container, false);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mRecommendPhone = view.findViewById(R.id.recommend_phone);
        mMobileInputView = view.findViewById(R.id.mobile_input_view);
        mGetAuthCodeBtn = view.findViewById(R.id.get_auth_code_btn);
        mVerifyCodeView = view.findViewById(R.id.verify_code_view);
        mPasswordInputView = view.findViewById(R.id.password_input_view);
        mAgreeServiceCheckBox = view.findViewById(R.id.agree_service_check_box);
        mPrivacyView = view.findViewById(R.id.privacy_view);
        mNextStepBtn = view.findViewById(R.id.btn_confirm);
        mPasswordInputViewAgain = view.findViewById(R.id.password_inputView_again);
        mToolbar = view.findViewById(R.id.toolbar);
        mTitleTxt = view.findViewById(R.id.toolbar_title);
        mLoginTxt = view.findViewById(R.id.txt_login);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Intent intent = new Intent(getActivity(), TimerService.class);
        getActivity().bindService(intent, conn, Context.BIND_AUTO_CREATE);
        initView();
        initListener();
    }

    private void initView() {
        String txt = mLoginTxt.getText().toString();
        SpannableString str = new SpannableString(txt);
        str.setSpan(new ClickableSpan() {
            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                // 设置文字颜色
                ds.setColor(getActivity().getResources().getColor(R.color.red));
                // 去掉底部下划线
                ds.setUnderlineText(false);
            }

            @Override
            public void onClick(View widget) {
                switchFragment(RegisterFragment.this, new LoginFragment());
            }
        },
        txt.indexOf(",") + 1,
        txt.length(),
        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        mLoginTxt.setMovementMethod(LinkMovementMethod.getInstance());
        mLoginTxt.setText(str);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().getSupportFragmentManager().popBackStack();
            }
        });
        mToolbar.setNavigationIcon(R.mipmap.icon_back_white);
        mTitleTxt.setText("商家注册");
    }

    private void initListener() {
        CustomTextWatcher textWatcher = new CustomTextWatcher();
        mMobileInputView.addTextChangedListener(textWatcher);
        mVerifyCodeView.addTextChangedListener(textWatcher);
        mPasswordInputView.addTextChangedListener(textWatcher);
        mPasswordInputViewAgain.addTextChangedListener(textWatcher);
        mAgreeServiceCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked && !checkInput()) {
                    mNextStepBtn.setEnabled(true);
                } else {
                    mNextStepBtn.setEnabled(false);
                }
            }
        });
        mGetAuthCodeBtn.setOnClickListener(this);
        mNextStepBtn.setOnClickListener(this);
        mPrivacyView.setOnClickListener(this);
    }

    private void unbindService() {
        if (null != getActivity() && null != conn && isBind) {
            try {
                getActivity().unbindService(conn);
            } catch (Exception e) {
                Log.e(TAG, e.toString());
            }
            isBind = false;
        }
    }

    @Override
    public void onClick(View v) {
        String mobileNumber = mMobileInputView.getText().toString();
        String password = mPasswordInputView.getText().toString();
        String verifyCode = mVerifyCodeView.getText().toString();

        switch (v.getId()) {
            case R.id.btn_confirm:
                if (!StringUtil.isValidatePhoneNumber(mobileNumber)) {
                    ToastUtil.getInstance().showToast("请输入正确的手机号码");
                    return;
                } else if (!StringUtil.isValidateVerifyCode(verifyCode)) {
                    ToastUtil.getInstance().showToast("验证码错误");
                    return;
                } else if (TextUtils.isEmpty(password) || password.contains(" ")
                        || password.length() < 6 || password.length() > 16) {
                    ToastUtil.getInstance().showToast("密码不能包含空格，并且在6-16位字符之间");
                    return;
                } else if (!mPasswordInputView.getText().toString()
                        .equals(mPasswordInputViewAgain.getText().toString())) {
                    ToastUtil.getInstance().showToast("两次密码不相同");
                    return;
                }
                SoftInputUtil.get().hideSoftKeyboard(getActivity());
                register(mobileNumber, verifyCode, password);
                break;

            case R.id.get_auth_code_btn:
                if (StringUtil.isValidatePhoneNumber(mobileNumber)) {
                    mGetAuthCodeBtn.setEnabled(false);
                    getSmsCode(mobileNumber);
                } else {
                    ToastUtil.getInstance().showToast("请输入正确的手机号码");
                    return;
                }
                break;

            case R.id.privacy_view:
                String title = "聚惠侠软件许可及服务协议";
                String loadUrl = "https://jypay-center.join51.com/jhx-xcxpay-h5-v2/o2oAgre.html";
                FragmentAboutApp fragmentAboutApp = FragmentAboutApp.newInstance(loadUrl, title);
                switchFragment(this, fragmentAboutApp);
                break;
            default:

                break;
        }
    }

    private void register(final String mobileNumber, String verifyCode, String password) {
        showLoadingDialog();
        String recommendPhone = null;
        if(!TextUtils.isEmpty(mRecommendPhone.getText())) {
            recommendPhone = mRecommendPhone.getText().toString();
        }
        mCall = ApiManager.get().getApiService(ApiService.class)
                .register(mobileNumber, verifyCode, StringUtil.encodeToSHA256(password), USER_TYPE, recommendPhone, registerParams());
        HttpRequest.getRequest().autoRecycle(this).start(mCall, new ResponseCallback<UserData>() {

            @Override
            public void onSuccess(String url, UserData data) {
                dismissDialog();
                if (data == null) {
                    return;
                }
                data.getUser().setPhone(mobileNumber);
                UserManager.get().setUser(data.getUser());
                SimpleCache.Companion.put(Constants.TOKEN_ID, data.getTokenID());
                SimpleCache.Companion.put(Constants.IS_LOGIN, true);
                if(!TextUtils.isEmpty(data.getRecommendPhone())) {
                    SimpleCache.Companion.put(Constants.RECOMMEND_PHONE,
                            data.getRecommendPhone());
                }
                SimpleCache.Companion.put(Constants.PAY_MONEY_URL, data.getPayMoneyUrl());
                Intent intent = new Intent(getActivity(), MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                startActivity(intent);
                dismissDialog();
                getActivity().finish();
            }

            @Override
            public void onError(String url, int errorCode, String errorMsg) {
                super.onError(url, errorCode, errorMsg);
                dismissDialog();
            }
        });
    }

    public Map<String, String> registerParams() {
        Map<String, String> req = new HashMap<>();
        DeviceInfo deviceInfo = SystemUtil.getDeviceInfo();
        if (!TextUtils.isEmpty(deviceInfo.getOSVersion())) {
            req.put("clientOS", deviceInfo.getOSVersion());
        }
        if (!TextUtils.isEmpty(deviceInfo.getNetworkType())) {
            req.put("clientNet", deviceInfo.getNetworkType());
        }
        if (!TextUtils.isEmpty(deviceInfo.getMAC())) {
            req.put("macAddress", deviceInfo.getMAC());
        }
        if(!TextUtils.isEmpty(MApplication.getVersion())) {
            req.put("version", MApplication.getVersion());
        }
        // 表示Android平台
        req.put("clientType", "1");
        req.put("clientName", "Android");
        return req;
    }

    /**
     * 检查输入
     * @return
     */
    private Boolean checkInput() {
        return TextUtils.isEmpty(mMobileInputView.getText().toString())
                || TextUtils.isEmpty(mVerifyCodeView.getText().toString())
                || TextUtils.isEmpty(mPasswordInputView.getText().toString())
                || TextUtils.isEmpty(mPasswordInputViewAgain.getText().toString());
    }

    private void EventPost(String phone) {
        EventBean<String> eb = new EventBean<>();
        eb.setEvent(phone);
        eb.setStatus(EventBean.STATUS_REGISTER);
        EventBus.getDefault().post(eb);
    }

    private void showCountDownView() {
        if (timerServiceBinder.getTimerServiceState() == TimerService.STOP) {
            timerServiceBinder.resumeTimerService();
        } else {
            timerServiceBinder.startTimerService();
        }
        mGetAuthCodeBtn.setText(TOTAL_COUNT_TIME + "s");
        timerServiceBinder.setOnRemainTimeChangeListener(new TimerService.OnRemainTimeChangeListener() {
            @Override
            public void onRemainTimeChanged(final int remainTime) {
                if (getActivity() == null) {
                    return;
                }
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (mGetAuthCodeBtn == null) {
                            return;
                        }
                        if (remainTime > 0) {
                            mGetAuthCodeBtn.setText(remainTime + "s");
                        } else {
                            mGetAuthCodeBtn.setText("重新获取");
                            mGetAuthCodeBtn.setEnabled(true);
                        }
                    }
                });
            }
        });
    }

    private void getSmsCode(String mobileNumber) {
        showLoadingDialog();
        call = ApiManager.get().getApiService(ApiService.class)
                .getSmsCode(mobileNumber, 1);
        HttpRequest.getRequest().autoRecycle(this).start(call, new ResponseCallback<SmsCode>() {

            @Override
            public void onSuccess(String url, SmsCode data) {
                dismissDialog();
                ToastUtil.getInstance().showToast(getActivity(), "获取验证码成功");
                //请求完成后再去启动倒计时
                if (isBind) {
                    showCountDownView();
                }
            }

            @Override
            public void onError(String url, int errorCode, String errorMsg) {
                super.onError(url, errorCode, errorMsg);
                dismissDialog();
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (timerServiceBinder != null && timerServiceBinder.getTimerServiceState() == TimerService.START) {
            mGetAuthCodeBtn.setEnabled(false);
            mGetAuthCodeBtn.setText(timerServiceBinder.getRemainTime() + "s");
        }
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
    }


    @Override
    public void onDestroy() {
        if (null != timerServiceBinder) {
            timerServiceBinder.destroyTimerService();
        }
        unbindService();
        super.onDestroy();
    }

    @Override
    public void onDestroyView() {
        if (null != timerServiceBinder) {
            timerServiceBinder.destroyTimerService();
        }
        unbindService();
        super.onDestroyView();
    }

    private class CustomTextWatcher implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if(checkInput() || !mAgreeServiceCheckBox.isChecked()) {
                mNextStepBtn.setEnabled(false);
            } else {
                mNextStepBtn.setEnabled(true);
            }
        }
    }
}
